﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UserControl;

namespace edu.Web
{
    public partial class SSO : System.Web.UI.Page
    {
        public string format = "", api_key = "", secret = "", url = "", result = "";
        DiscuzSession ds;
        protected void Page_Load(object sender, EventArgs e)
        {
        
            if (Session["DS"] != null)
            {
                ds = (DiscuzSession)Session["DS"];
            }
            else
            {
                ds = new DiscuzSession(api_key, secret, url);
            }
            if (Request.QueryString["auth_token"] != null && Request.QueryString["auth_token"].ToString() != "")
            {
                //登录，成功后自动返回
                try
                {
                    ds.session_info = ds.GetSessionFromToken(Request.QueryString["auth_token"].ToString());
                    Session["DS"] = ds;
                    Response.Redirect("/dailyActionForParent.aspx");
                }
                catch {
                }

                //告诉用户登录成功
                //Page.RegisterStartupScript("script", "<script>alert('登录成功');</script>");
            }

             //如果没有session，模拟登录
            if (ds.session_info == null||Util.GetQueryString("user_status") == "0")
            {
                string remoteLoginUrl = string.Format("{0}login.aspx?api_key={1}&", url, api_key);
                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                client.OpenRead(remoteLoginUrl, string.Format("username={0}&password={1}&login=",Session["username"].ToString(),Session["username"].ToString()));
  
                //第二次Get请求，从第一次的response中获取cookie
                client.RequestHeaders.Add("Cookie", client.Cookie);
                result = client.OpenRead(remoteLoginUrl);

                //从返回结果中拿到带有auto_token的跳转链接
                try
                {
                    int j = result.IndexOf("<a href=\"") + 9;
                    int k = result.IndexOf("\">here</a>");
                    Response.Redirect(result.Substring(j, k - j), false);
                }
                catch (Exception ex)
                {
                    string ss = ex.Message.ToString();
                    Response.Redirect("home.aspx");
                }

                return;
            }  
        }
        
    }
}